package main

import (
	"database/sql"
	"fmt"
	pb "ihos/ihos"
	"log"
)

type jiuzhenren struct {
	id      int32 //PK
	xm      string
	xb      int32
	sfz     string
	sjhm    string
	hzid    int32
	removed bool
}

func (w *jiuzhenren) GetFromDB(id int32) error {
	sql := "SELECT id,xm,xb,sfz,sjhm,hzid,removed FROM jiuzhenren WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.xm, &w.xb, &w.sfz, &w.sjhm, &w.hzid, &w.removed)
}

func (w *jiuzhenren) RemoveAllByHz(hz_id int32) {
	sql := "DELETE FROM jiuzhenren where hzid=$1"
	DBConn.db.Exec(sql, hz_id)
}

func (w *jiuzhenren) GetByHz(hz_id int32) (jrzs []*jiuzhenren, err error) {
	//sql := "SELECT id,xm,xb,sfz,sjhm,hzid,removed FROM jiuzhenren WHERE hzid=$1"
	//return DBConn.db.QueryRow(sql, hz_id).Scan(&w.id, &w.xm, &w.xb, &w.sfz, &w.sjhm, &w.hzid, &w.removed)
	log.Println("GetByHz", hz_id)
	var rows *sql.Rows
	out := make([]*jiuzhenren, 0)
	sqlStr := ""
	if w.id > 0 {
		sqlStr = "SELECT id,xm,xb,sfz,sjhm,hzid,removed FROM jiuzhenren WHERE id=" + fmt.Sprint(w.id)
	} else {
		sqlStr = "SELECT id,xm,xb,sfz,sjhm,hzid,removed FROM jiuzhenren"
		cond := make([]string, 0)
		if hz_id > 0 {
			cond = append(cond, "hzid="+fmt.Sprint(hz_id))
		}
		if len(cond) > 0 {
			sqlStr += " WHERE "
			sep := ""
			for _, v := range cond {
				sqlStr += sep + v
				sep = " AND "
			}
		}
		sqlStr += " ORDER BY id DESC LIMIT 100"
	}
	// log.Println("SQL:", sqlStr)
	rows, err = DBConn.db.Query(sqlStr)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		w := &jiuzhenren{}
		if err = rows.Scan(&w.id, &w.xm, &w.xb, &w.sfz, &w.sjhm, &w.hzid, &w.removed); err != nil {
			log.Println(err)
		} else {
			out = append(out, w)
		}
	}
	return out, nil
}

func (w *jiuzhenren) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE jiuzhenren set removed=$1 where id=$2 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.removed, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO jiuzhenren(xm,xb,sfz,sjhm,hzid) VALUES($1,$2,$3,$4,$5) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.xm, w.xb, w.sfz, w.sjhm, w.hzid).Scan(&w.id)
	}
	return err
}

func (w *jiuzhenren) toPB() *pb.JiuZhenRenInfoL1 {
	return &pb.JiuZhenRenInfoL1{
		ID:      w.id,
		XM:      w.xm,
		XB:      pb.GENDER(w.xb),
		SFZ:     w.sfz,
		SJHM:    w.sjhm,
		OID:     w.hzid,
		REMOVED: w.removed,
	}
}

func (w *jiuzhenren) fromPB(jzr *pb.JiuZhenRenInfoL1) *jiuzhenren {
	w.id = jzr.GetID()
	w.xm = jzr.GetXM()
	w.xb = int32(jzr.GetXB())
	w.sfz = jzr.GetSFZ()
	w.sjhm = jzr.GetSJHM()
	w.hzid = jzr.GetOID()
	w.removed = jzr.GetREMOVED()
	return w
}
